package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("FoodmaterialRestController")
public class FoodmaterialRestController extends CmiEmaController {

	/**
	 * Create a new Foodmaterial entity
	 * 
	 */
	@RequestMapping(value = "/newFoodmaterial", method = RequestMethod.POST)
	@ResponseBody
	public Object newFoodmaterial(@RequestBody Foodmaterial foodmaterial) {
		foodmaterialService.saveFoodmaterial(foodmaterial);
		return JSONObject
				.parse(cmiPsonService.toJsonString(foodmaterialDAO.findFoodmaterialByPrimaryKey(foodmaterial.getId()), 2));
	}

	@RequestMapping(value = "/restNewFoodmaterial", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewFoodmaterial(@RequestBody String foodmaterialJson) {
		Foodmaterial foodmaterial = new Gson().fromJson(foodmaterialJson, Foodmaterial.class);
		appendReferences(foodmaterial);
		foodmaterialService.saveFoodmaterial(foodmaterial);
		return JSONObject
				.parse(cmiPsonService.toJsonString(foodmaterialDAO.findFoodmaterialByPrimaryKey(foodmaterial.getId()), 2));
	}

	@RequestMapping(value = "/saveFoodmaterial", method = RequestMethod.PUT)
	@ResponseBody
	public Foodmaterial saveFoodmaterial(@RequestBody Foodmaterial foodmaterial) {
		foodmaterialService.saveFoodmaterial(foodmaterial);
		return foodmaterialDAO.findFoodmaterialByPrimaryKey(foodmaterial.getId());
	}

	@RequestMapping(value = "/restSaveFoodmaterial", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveFoodmaterial(@RequestBody String foodmaterialJson) {
		Foodmaterial foodmaterial = new Gson().fromJson(foodmaterialJson, Foodmaterial.class);
		appendReferences(foodmaterial);
		CmiPsonService cmiPsonService = new CmiPsonService();
		foodmaterialService.saveFoodmaterial(foodmaterial);
		return JSONObject
				.parse(cmiPsonService.toJsonString(foodmaterialDAO.findFoodmaterialByPrimaryKey(foodmaterial.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteFoodmaterial/{foodmaterialId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteFoodmaterial(@PathVariable Integer foodmaterialId) {
		Foodmaterial foodmaterial = foodmaterialDAO.findFoodmaterialByPrimaryKey(foodmaterialId);
		foodmaterialService.deleteFoodmaterial(foodmaterial);
	}

	@RequestMapping(value = "/restConfirmDeleteFoodmaterials")
	@ResponseBody
	public Object restConfirmDeleteFoodmaterials(@RequestBody Set<Integer> deleteFoodmaterialsIds) {
		Set<Foodmaterial> deleteFoodmaterials = foodmaterialDAO.findFoodmaterialsByIds(deleteFoodmaterialsIds);
		Set<Foodmaterial> referencedFoodmaterials = foodmaterialService.loadReferenceFoodmaterials(deleteFoodmaterials);
		deleteFoodmaterials.removeAll(referencedFoodmaterials);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedFoodmaterials);
		jsonObject.put("deleteEntitys", deleteFoodmaterials);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteFoodmaterials")
	@ResponseBody
	public Object restDeleteFoodmaterials(@RequestBody Set<Foodmaterial> deleteFoodmaterials) {
		Iterator<Foodmaterial> iterator = deleteFoodmaterials.iterator();
		while (iterator.hasNext()) {
			Foodmaterial currentFoodmaterial = iterator.next();
			foodmaterialService.deleteFoodmaterial(currentFoodmaterial);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listFoodmaterials");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadFoodmaterial/{foodmaterialId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodmaterial(@PathVariable Integer foodmaterialId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(foodmaterialDAO.findFoodmaterialByPrimaryKey(foodmaterialId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodmaterialFood/{foodmaterialId}/food", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodmaterialFood(@PathVariable Integer foodmaterialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodmaterialDAO.findFoodmaterialByPrimaryKey(foodmaterialId).getFood(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodmaterialMaterial/{foodmaterialId}/material", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodmaterialMaterial(@PathVariable Integer foodmaterialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodmaterialDAO.findFoodmaterialByPrimaryKey(foodmaterialId).getMaterial(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	public void appendReferences(Foodmaterial foodmaterial) {

		Food food = foodmaterial.getFood();
		if (food != null)
			foodmaterial.setFood(foodService.findFoodByPrimaryKey(food.getId()));

		Material material = foodmaterial.getMaterial();
		if (material != null)
			foodmaterial.setMaterial(materialService.findMaterialByPrimaryKey(material.getId()));

	}

	@RequestMapping(value = "/restGetFoodmaterialFood/{foodmaterialId}/food", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodmaterialFood(@PathVariable Integer foodmaterialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodmaterialDAO.findFoodmaterialByPrimaryKey(foodmaterialId).getFood(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodmaterialMaterial/{foodmaterialId}/material", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodmaterialMaterial(@PathVariable Integer foodmaterialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodmaterialDAO.findFoodmaterialByPrimaryKey(foodmaterialId).getMaterial(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListFoodmaterials", method = RequestMethod.GET)
	@ResponseBody
	public Object restListFoodmaterials() {
		return JSONObject.parse(cmiPsonService.toJsonString(foodmaterialService.loadFoodmaterials(), 2));
	}

	@RequestMapping(value = "/restListFoodmaterialsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListFoodmaterialsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = foodmaterialPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Foodmaterial> foodmaterials = foodmaterialDAO.findAllFoodmaterials(startResult,
				cmiPagination.getPaginationSize());
		String foodmaterialString = cmiPsonService.toPsonString(foodmaterials, 2, cmiPagination);

		return JSONObject.parse(foodmaterialString);
	}

	@RequestMapping("/foodmaterialSelectBox")
	@ResponseBody
	public JSONObject foodmaterialSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Food":
				entitySet = foodService.loadFoodsByIdSet(searchValue);
				break;
			case "Material":
				entitySet = materialService.loadMaterialsByIdSet(searchValue);
				break;

			// 被引用键
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Food":
				entitySet = foodDAO.findAllFoods((pageNumber - 1) * paginationSize, paginationSize);
				count = foodService.countFoods();
				break;
			case "Material":
				entitySet = materialDAO.findAllMaterials((pageNumber - 1) * paginationSize, paginationSize);
				count = materialService.countMaterials();
				break;

			// 被引用键
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Food":
				entitySet = foodDAO.findFoodByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodService.countFoodsByName(queryword);
				break;
			case "Material":
				entitySet = materialDAO.findMaterialByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = materialService.countMaterialsByName(queryword);
				break;

			// 被引用键
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
